package com.stcc.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * 描述:穿透代理获取真实用户ip
 * 项目名:wisdom_match-parent
 * 包名:com.tydic.portal.util
 * 作者:stcc
 * 创建时间:2021/4/14 17:24
 * 版本:1.0
 */

public class IpAddressUtil {
    private static final Logger logger = LoggerFactory.getLogger(IpAddressUtil.class);

    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     */
    public static String getIpAddress(HttpServletRequest request) {

        // 获取nginx代理前的ip地址
        String ip = request.getHeader("x-forwarded-for");
        logger.info("x-forwarded-for request ip : {}", ip);
        if(ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            logger.info("Proxy-Client-IP request ip : {}", ip);
        }
        if (ip == null || ip.length () == 0 || "unknown".equalsIgnoreCase (ip)) {
            ip = request.getHeader ("WL-Proxy-Client-IP");
            logger.info("WL-Proxy-Client-IP request ip : {}", ip);
        }
        if (ip == null || ip.length () == 0 || "unknown".equalsIgnoreCase (ip)) {
            ip = request.getRemoteAddr ();
            if (ip.equals ("127.0.0.1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost ();

                } catch (Exception e) {
                    e.printStackTrace ();
                }
                ip = inet != null ? inet.getHostAddress() : null;
                logger.info("getLocalHost request ip : {}", ip);
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length () > 15) {
            if (ip.indexOf (",") > 0) {
                ip = ip.substring (0, ip.indexOf (","));
            }
        }
        logger.info("final request ip : {}", ip);
        return ip;

    }
}
